<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.mobile" placeholder="用户手机号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.store_name" placeholder="店铺名称"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.store_mobile" placeholder="店铺手机号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.master_name" placeholder="推广用户（后台）"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.is_cancellation" placeholder="账户是否注销" clearable class="">
          <el-option v-for="item in selectWhether" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="mobile" label="手机号" align="center"> </el-table-column>
      <el-table-column prop="store" label="绑定店铺信息" align="center">
        <template #default="scope">
          <div class="ibDraggable" v-if="scope.row.store !== null">
            <div>店铺：{{ scope.row.store.name }}</div>
            <div>手机号：{{ scope.row.store.mobile }}</div>
          </div>
          <div class="ibDraggable" v-else>
            <div>--</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="promoter_user_mobile" label="推广用户（前端）" align="center"> </el-table-column>
      <el-table-column prop="master_name" label="推广用户（后台）" align="center"> </el-table-column>
      <el-table-column prop="reg_time" label="创建时间" align="center" :formatter="(row: IUserList) => handleVerifyFormatDate(row.reg_time)"> </el-table-column>
      <el-table-column prop="is_cancellation" label="账户状态" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.is_cancellation === 0 ? 'success' : scope.row.is_cancellation === 1 ? 'danger' : 'primary'">{{ scope.row.is_cancellation === 0 ? "正常" : "注销" }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'edit'" @click="handleViewEdit(scope.row, 'edit')">编辑</el-button>
            <div v-permission="'delete'">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.id])">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-permission="'unbind'" v-if="scope.row.store !== null">
              <el-popconfirm placement="top" width="160" title="你确定要解绑店铺吗?" @confirm="handleUnboundStore(scope.row)">
                <template #reference>
                  <el-button type="primary" link :icon="Link">解绑店铺</el-button>
                </template>
              </el-popconfirm>
            </div>
            <el-button type="primary" link :icon="EditPen" v-permission="'changeMobile'" @click="handleChangePhone(scope.row)">手机号</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>

    <!-- 修改手机号弹框 -->
    <ChangePhoneDialog v-model:dialog="dialogVisible" v-model:form="changePhoneForm" @handleSuccess="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
import ChangePhoneDialog from "@/components/user/appUserInfo/ChangePhoneDialog.vue";
import { View, Delete, EditPen, Search, Refresh, Link } from "@element-plus/icons-vue";
import { deleteUserInfo } from "@/utils/api/master";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { ViewModeFilter } from "@/types/common";
import { getAppUserInfo, putAppUserUnbindStoreInfo } from "@/utils/api/user";
import type { IChangeUserPhone, IUserList, IUserSearch } from "@/types/user";
import type { IDictData } from "@/types/dict";
import { useState } from "@/hooks/useState.ts";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectWhether: Array<IDictData>;
}
const { selectWhether } = defineProps<Props>();
// const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});

const dialogVisible = ref(false);

const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const total = ref(0);
const searchCondition = reactive<IUserSearch>({
  mobile: "",
  store_name: "",
  store_mobile: "",
  master_name: "",
  is_cancellation: "",
  size: 10,
  current: 1
});
const tableList = ref<Array<IUserList>>([]);

/* 修改手机号数据 */
const changePhoneForm = reactive<IChangeUserPhone>({
  id: 0,
  mobile: ""
});

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.mobile = "";
  searchCondition.store_name = "";
  searchCondition.store_mobile = "";
  searchCondition.master_name = "";
  searchCondition.is_cancellation = "";
  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}

/**
 * 切换表单状态（ 添加、编辑、查看 ，隐藏none ）
 */
// function changeFormStatus(state: ViewMode) {
//   formStatus.value = state;
// }

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getAppUserInfo<IUserList, IUserSearch>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number | null) {
  /* if (val === null) return; 后端分页，缓存路由activated请求的时候做的兼容 */
  if (val === null) return;
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IUserList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IUserList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 删除后的信息 */
function deleteInfo(idArray: Array<number>) {
  toggleState(true);
  deleteUserInfo({ idArray })
    .then(() => {
      /* 当删除成功后，删除对应选中的数据或单个数据 */
      tableList.value = tableList.value.filter((item: IUserList) => !idArray.includes(item.id));
      ElMessage.success(`成功删除了${idArray.length}条数据`);
      multipleTableRef.value!.clearSelection();
      total.value = total.value - idArray.length;
    })
    .catch((error: Error) => {
      console.log(error);
    })
    .finally(() => {
      toggleState(false);
    });
}
/* 解绑店铺 */
function handleUnboundStore(row: IUserList) {
  toggleState(true);
  putAppUserUnbindStoreInfo({ id: row.id })
    .then(() => {
      searchInfo();
      ElMessage.success("解绑成功");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 修改手机号 */
function handleChangePhone(row: IUserList) {
  console.log(row.mobile);
  changePhoneForm.id = row.id;
  dialogVisible.value = true;
}
/* 修改成功 */
function handleSuccess() {
  getTableInfo();
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}
</style>
